/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2013 All Rights Reserved.
 */
package com.h2o3.carmack.session;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.glassfish.grizzly.websockets.WebSocket;

import com.h2o3.carmack.message.MessageSerializer;

/**
 * @author chensheng
 * @version $Id: SessionFactory.java, v 0.1 12/6/13 11:02 PM chensheng Exp $
 */
public final class SessionFactory {
    private DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    private Random     random     = new Random();

    private int        seq;

    private String generateSessionKey() {
        int sid;

        synchronized (this) {
            seq++;
            sid = seq;

            if (seq == Integer.MAX_VALUE) {
                seq = 0;
            }
        }

        return dateFormat.format(new Date()).concat("-").concat(Integer.toHexString(sid))
            .concat("-").concat(Integer.toHexString(random.nextInt()));
    }

    private static SessionFactory sessionFactory = new SessionFactory();

    public static SessionFactory getInstance() {
        return sessionFactory;
    }

    public Session createSession(WebSocket socket, MessageSerializer messageSerializer) {
        return new Session(generateSessionKey(), socket, messageSerializer);
    }
}
